/*
 * Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.greenrobot.eventbus;

import android.text.TextUtils;

import org.greenrobot.eventbus.meta.SubscriberInfoIndex;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;

/**
 * EventBus is a central publish/subscribe event system for Android. Events are posted ({@link #post(Object)}) to the
 * bus, which delivers it to subscribers that have a matching handler method for the event type. To receive events,
 * subscribers must register themselves to the bus using {@link #register(Object)}. Once registered, subscribers
 * receive events until {@link #unregister(Object)} is called. Event handling methods must be annotated by
 * {@link Subscribe}, must be public, return nothing (void), and have exactly one parameter
 * (the event).
 *
 * @author Markus Junginger, greenrobot
 */
public class EventBus {

    /** Log tag, apps may override it. */
    public static String TAG = "EventBus";
    public static final String CLASS_NAME_AUTO_REGISTER = "EventBusAutoRegister";
    public static final String CLASS_NAME_INDEX = "EventBusIndexes";
    public static final String METHOD_NAME_AUTO_REGISTER = "register";

    static volatile EventBus defaultInstance;

    private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
    private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();

    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    private final Map<Class<?>, Object> stickyEventsByType;

    // harryguo add start. shall end with "// harryguo add end"
    private final Map<String, CopyOnWriteArrayList<Subscription>> subscriptionsByEventFilter = new HashMap<>();
    private final Map<Object, List<String>> filtersBySubscriber = new HashMap<>();
    private final Map<String, Object> stickyEventsByFilter = new ConcurrentHashMap<>();
    // harryguo add end. shall begin with "// harryguo add start"

    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

    // @Nullable
    private final MainThreadSupport mainThreadSupport;
    // @Nullable
    private final Poster mainThreadPoster;
    private final BackgroundPoster backgroundPoster;
    private final AsyncPoster asyncPoster;
    private final SubscriberMethodFinder subscriberMethodFinder;
    private final ExecutorService executorService;

    private final boolean throwSubscriberException;
    private final boolean logSubscriberExceptions;
    private final boolean logNoSubscriberMessages;
    private final boolean sendSubscriberExceptionEvent;
    private final boolean sendNoSubscriberEvent;
    private final boolean eventInheritance;

    private final int indexCount;
    private final Logger logger;

    /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        EventBus instance = defaultInstance;
        if (instance == null) {
            synchronized (EventBus.class) {
                instance = EventBus.defaultInstance;
                if (instance == null) {
                    instance = EventBus.defaultInstance = new EventBus();
                }
            }
        }
        return instance;
    }

    public static EventBusBuilder builder() {
        return new EventBusBuilder();
    }

    /** For unit test primarily. */
    public static void clearCaches() {
        SubscriberMethodFinder.clearCaches();
        eventTypesCache.clear();
    }

    /**
     * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
     * central bus, consider {@link #getDefault()}.
     */
    public EventBus() {
        this(DEFAULT_BUILDER);
    }

    EventBus(EventBusBuilder builder) {
        logger = builder.getLogger();
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEventsByType = new ConcurrentHashMap<>();
        mainThreadSupport = builder.getMainThreadSupport();
        mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;

        autoRegisterForOnce();
    }

    private volatile boolean mHasAutoRegistered = false;
    /**
     *  harryguo 是否自动注册过了。不能定义为static，要确保：每个EventBus的instance里都进行了自动注册。无论用户通过哪个instance来post或process事件，都可以调用到这里来
     *  本函数放在register里面是达不到预期效果的，理由：1. 用户没调用register的话，就无法对静态订阅者注册了；2. 调用register之前，hasSubscriberForEvent()返回的将是空
     */
    private void autoRegisterForOnce() {
        if (!mHasAutoRegistered) {
            synchronized (this) {
                if (!mHasAutoRegistered) {
                    // harryguo 这一行必须在最前。因为这里比较关键，搞错了就会形成无限循环调用
                    mHasAutoRegistered = true;
                    try {
                        Class autoRegister = Class.forName(EventBus.class.getPackage().getName() + "." + CLASS_NAME_AUTO_REGISTER);
                        if (autoRegister != null) {
                            Method registerMethod = autoRegister.getDeclaredMethod(METHOD_NAME_AUTO_REGISTER, EventBus.class);
                            if (registerMethod != null)
                                registerMethod.invoke(null, this);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 设置一个 SubscriberInfoIndex 给 {@link #subscriberMethodFinder} 如果它还一个都没有的话
     */
    public void setSubscribeIndexIfNone(SubscriberInfoIndex index) {
        subscriberMethodFinder.setSubscribeIndexIfNone(index);
    }

    /**
     * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
     * are no longer interested in receiving events.
     * <p/>
     * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
     * The {@link Subscribe} annotation also allows configuration like {@link
     * ThreadMode} and priority.
     */
    public void register(Object subscriber) {
        Class<?> subscriberClass;
        // harryguo add start. shall end with "// harryguo add end"
        // 允许调用者注册静态函数类型的订阅者
        if (subscriber instanceof Class<?>)
            subscriberClass = (Class<?>) subscriber;
        else
            subscriberClass = subscriber.getClass();
        // harryguo add end. shall begin with "// harryguo add start"
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                // harryguo add start. shall end with "// harryguo add end"
                // subscribe(subscriber, subscriberMethod);
                boolean subscriberIsClass = (subscriber instanceof Class<?>);
                boolean isStaticMethod = ((subscriberMethod.method.getModifiers() & Modifier.STATIC) != 0);
                // 如果register的是类class（XXX.class），而非类的实例(XXX xxx = new XXX())，也行，但这种注册方式里，仅支持注册静态函数（因为没有实例，无法调用非静态函数）
                if (subscriberIsClass != isStaticMethod)
                    continue;
                    // 如果是排他性的订阅者，那就要把已经注册了该事件的其他订阅者先删除掉
                // 将其他所有同类Subscrible(什么是同类：eventFilter相同；eventFilter都为空，而event事件是同一个class)踢出去
                if (subscriberMethod.exclusive) {
                    if (!TextUtils.isEmpty(subscriberMethod.eventFilter))
                        unsubscribeByEventFilter(null, subscriberMethod.eventFilter);
                    else
                        unsubscribeByEventType(null, subscriberMethod.eventType);
                }
                // 允许调用者注册带eventFilter的订阅者
                if (!TextUtils.isEmpty(subscriberMethod.eventFilter))
                    subscribeByEventFilter(subscriber, subscriberMethod);
                else
                    subscribeByEventType(subscriber, subscriberMethod);
                // harryguo add end. shall begin with "// harryguo add start"
            }
        }
    }

    // Must be called in synchronized block
    private void subscribeByEventType(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.size() > 0) {
                Subscription subscription = subscriptions.get(0);
                // 已经存在一个订阅者了，而且这个订阅者比较大牌，是排他的，所以其他的订阅者就不能再加进来了。
                if (subscription.subscriberMethod.exclusive)
                    return;
            }
            // harryguo: 这是多余代码所以我注释了，理由：newSubscription是新new出来的，subscriptions当然不可能会contains它啊
//            if (subscriptions.contains(newSubscription)) {
//                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
//                        + eventType);
//            }
        }

        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // Existing sticky events of all subclasses of eventType have to be considered.
                // Note: Iterating over all events may be inefficient with lots of sticky events,
                // thus data structure should be changed to allow a more efficient lookup
                // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
                Set<Map.Entry<Class<?>, Object>> entries = stickyEventsByType.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    Class<?> candidateEventType = entry.getKey();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEventsByType.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

    private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
            // --> Strange corner case, which we don't take care of here.
            postToSubscription(newSubscription, stickyEvent, isMainThread());
        }
    }

    /**
     * Checks if the current thread is running in the main thread.
     * If there is no main thread support (e.g. non-Android), "true" is always returned. In that case MAIN thread
     * subscribers are always called in posting thread, and BACKGROUND subscribers are always called from a background
     * poster.
     */
    private boolean isMainThread() {
        return mainThreadSupport != null ? mainThreadSupport.isMainThread() : true;
    }

    public synchronized boolean isRegistered(Object subscriber) {
        return typesBySubscriber.containsKey(subscriber) || filtersBySubscriber.containsKey(subscriber);
    }

    /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscriber == null || subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                    // harryguo：idsBySubscriber里的数据也要清一下
                    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscription.subscriber);
                    if (subscribedTypes != null) {
                        subscribedTypes.remove(eventType);
                        if (subscribedTypes.isEmpty())
                            typesBySubscriber.remove(subscription.subscriber);
                    }
                }
            }
            // harryguo: 如果订阅者都已经被删光了，那这个EventType的记录就可以整体被删掉了
            if (subscriptions.isEmpty())
                subscriptionsByEventType.remove(eventType);
        }
    }

    /** Unregisters the given subscriber from all event classes. */
    public synchronized void unregister(Object subscriber) {
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            typesBySubscriber.remove(subscriber);
        }

        // harryguo add start. shall end with "// harryguo add end"
        List<String> subscribedFilters = filtersBySubscriber.get(subscriber);
        if (subscribedFilters != null) {
            for (String eventFilter : subscribedFilters) {
                unsubscribeByEventFilter(subscriber, eventFilter);
            }
            filtersBySubscriber.remove(subscriber);
        }
        // harryguo add end. shall begin with "// harryguo add start"

        if (subscribedTypes == null && subscribedFilters == null)
        {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

    /** Posts the given event to the event bus. */
    // harryguo comment this，挪到harryguo的专有代码块去
//    public void post(Object event) {
//        PostingThreadState postingState = currentPostingThreadState.get();
//        List<PostingThreadState.EventMessage> eventQueue = postingState.eventQueue;
//        eventQueue.add(new PostingThreadState.EventMessage(event));
//
//        if (!postingState.isPosting) {
//            postingState.isMainThread = isMainThread();
//            postingState.isPosting = true;
//            if (postingState.canceled) {
//                throw new EventBusException("Internal error. Abort state was not reset");
//            }
//            try {
//                while (!eventQueue.isEmpty()) {
//                    postSingleEvent(eventQueue.remove(0), postingState);
//                }
//            } finally {
//                postingState.isPosting = false;
//                postingState.isMainThread = false;
//            }
//        }
//    }

    /**
     * Called from a subscriber's event handling method, further event delivery will be canceled. Subsequent
     * subscribers
     * won't receive the event. Events are usually canceled by higher priority subscribers (see
     * {@link Subscribe#priority()}). Canceling is restricted to event handling methods running in posting thread
     * {@link ThreadMode#POSTING}.
     */
    public void cancelEventDelivery(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        if (!postingState.isPosting) {
            throw new EventBusException(
                    "This method may only be called from inside event handling methods on the posting thread");
        } else if (event == null) {
            throw new EventBusException("Event may not be null");
        } else if (postingState.event != event) {
            throw new EventBusException("Only the currently handled event may be aborted");
        } else if (postingState.subscription.subscriberMethod.threadMode != ThreadMode.POSTING) {
            throw new EventBusException(" event handlers may only abort the incoming event");
        }

        postingState.canceled = true;
    }

    /**
     * Posts the given event to the event bus and holds on to the event (because it is sticky). The most recent sticky
     * event of an event's type is kept in memory for future access by subscribers using {@link Subscribe#sticky()}.
     */
    public void postSticky(Object event) {
        synchronized (stickyEventsByType) {
            stickyEventsByType.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }

    /**
     * Gets the most recent sticky event for the given type.
     *
     * @see #postSticky(Object)
     */
    public <T> T getStickyEvent(Class<T> eventType) {
        synchronized (stickyEventsByType) {
            return eventType.cast(stickyEventsByType.get(eventType));
        }
    }

    /**
     * Remove and gets the recent sticky event for the given event type.
     *
     * @see #postSticky(Object)
     */
    public <T> T removeStickyEvent(Class<T> eventType) {
        synchronized (stickyEventsByType) {
            return eventType.cast(stickyEventsByType.remove(eventType));
        }
    }

    /**
     * Removes the sticky event if it equals to the given event.
     *
     * @return true if the events matched and the sticky event was removed.
     */
    public boolean removeStickyEvent(Object event) {
        synchronized (stickyEventsByType) {
            Class<?> eventType = event.getClass();
            Object existingEvent = stickyEventsByType.get(eventType);
            if (event.equals(existingEvent)) {
                stickyEventsByType.remove(eventType);
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * Removes all sticky events.
     */
    public void removeAllStickyEvents() {
        synchronized (stickyEventsByType) {
            stickyEventsByType.clear();
        }
        synchronized (stickyEventsByFilter) {
            stickyEventsByFilter.clear();
        }
    }

    public boolean hasSubscriberForEvent(Class<?> eventClass) {
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        if (eventTypes != null) {
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                CopyOnWriteArrayList<Subscription> subscriptions;
                synchronized (this) {
                    subscriptions = subscriptionsByEventType.get(clazz);
                }
                if (subscriptions != null && !subscriptions.isEmpty()) {
                    return true;
                }
            }
        }
        return false;
    }

    private void postSingleEvent(PostingThreadState.EventMessage eventMsg, PostingThreadState postingState) throws Error {
        Object event = eventMsg.event;
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        // harryguo add. 这里如果eventFilter不为空，那就只根据eventFilter，忽略eventType。eventFilter优先级高于eventType
        if (!TextUtils.isEmpty(eventMsg.eventFilter))
        {
            subscriptionFound = postSingleEventForEventFilter(eventMsg, postingState);
        }
        else {
            if (eventInheritance) {
                List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
                int countTypes = eventTypes.size();
                for (int h = 0; h < countTypes; h++) {
                    Class<?> clazz = eventTypes.get(h);
                    subscriptionFound |= postSingleEventForEventType(eventMsg, postingState, clazz);
                }
            } else {
                subscriptionFound = postSingleEventForEventType(eventMsg, postingState, eventClass);
            }
        }
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

    private boolean postSingleEventForEventType(PostingThreadState.EventMessage eventMsg, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                postingState.event = eventMsg.event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    postToSubscription(subscription, eventMsg.event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }

    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case MAIN_ORDERED:
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    // temporary: technically not correct as poster not decoupled from subscriber
                    invokeSubscriber(subscription, event);
                }
                break;
            case BACKGROUND:
                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC:
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }

    /** Looks up all Class objects including super classes and interfaces. Should also work for interfaces. */
    private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
        synchronized (eventTypesCache) {
            List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
            if (eventTypes == null) {
                eventTypes = new ArrayList<>();
                Class<?> clazz = eventClass;
                while (clazz != null) {
                    eventTypes.add(clazz);
                    addInterfaces(eventTypes, clazz.getInterfaces());
                    clazz = clazz.getSuperclass();
                }
                eventTypesCache.put(eventClass, eventTypes);
            }
            return eventTypes;
        }
    }

    /** Recurses through super interfaces. */
    static void addInterfaces(List<Class<?>> eventTypes, Class<?>[] interfaces) {
        for (Class<?> interfaceClass : interfaces) {
            if (!eventTypes.contains(interfaceClass)) {
                eventTypes.add(interfaceClass);
                addInterfaces(eventTypes, interfaceClass.getInterfaces());
            }
        }
    }

    /**
     * Invokes the subscriber if the subscriptions is still active. Skipping subscriptions prevents race conditions
     * between {@link #unregister(Object)} and event delivery. Otherwise the event might be delivered after the
     * subscriber unregistered. This is particularly important for main thread delivery and registrations bound to the
     * live cycle of an Activity or Fragment.
     */
    void invokeSubscriber(PendingPost pendingPost) {
        Object event = pendingPost.event;
        Subscription subscription = pendingPost.subscription;
        PendingPost.releasePendingPost(pendingPost);
        if (subscription.active) {
            invokeSubscriber(subscription, event);
        }
    }

    void invokeSubscriber(Subscription subscription, Object event) {
        try {
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
        } catch (InvocationTargetException e) {
            handleSubscriberException(subscription, event, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }

    private void handleSubscriberException(Subscription subscription, Object event, Throwable cause) {
        if (event instanceof SubscriberExceptionEvent) {
            if (logSubscriberExceptions) {
                // Don't send another SubscriberExceptionEvent to avoid infinite event recursion, just log
                logger.log(Level.SEVERE, "SubscriberExceptionEvent subscriber " + subscription.subscriber.getClass()
                        + " threw an exception", cause);
                SubscriberExceptionEvent exEvent = (SubscriberExceptionEvent) event;
                logger.log(Level.SEVERE, "Initial event " + exEvent.causingEvent + " caused exception in "
                        + exEvent.causingSubscriber, exEvent.throwable);
            }
        } else {
            if (throwSubscriberException) {
                throw new EventBusException("Invoking subscriber failed", cause);
            }
            if (logSubscriberExceptions) {
                logger.log(Level.SEVERE, "Could not dispatch event: " + event.getClass() + " to subscribing class "
                        + subscription.subscriber.getClass(), cause);
            }
            if (sendSubscriberExceptionEvent) {
                SubscriberExceptionEvent exEvent = new SubscriberExceptionEvent(this, cause, event,
                        subscription.subscriber);
                post(exEvent);
            }
        }
    }

    /** For ThreadLocal, much faster to set (and get multiple values). */
    final static class PostingThreadState {
        final static private class EventMessage {
            Object event;
            String eventFilter;

            EventMessage(Object event, String eventFilter) {
                this.event = event;
                this.eventFilter = eventFilter;
            }
        }

        final List<EventMessage> eventQueue = new ArrayList<>();
        boolean isPosting;
        boolean isMainThread;
        Subscription subscription;
        Object event;
        boolean canceled;
    }

    ExecutorService getExecutorService() {
        return executorService;
    }

    /**
     * For internal use only.
     */
    public Logger getLogger() {
        return logger;
    }

    // Just an idea: we could provide a callback to post() to be notified, an alternative would be events, of course...
    /* public */interface PostCallback {
        void onPostCompleted(List<SubscriberExceptionEvent> exceptionEvents);
    }

    @Override
    public String toString() {
        return "EventBus[indexCount=" + indexCount + ", eventInheritance=" + eventInheritance + "]";
    }

    // harryguo start。以下全是harryguo的代码，有harryguo end做结束：
    // Must be called in synchronized block
    private void subscribeByEventFilter(Object subscriber, SubscriberMethod subscriberMethod) {
        String eventFilter = subscriberMethod.eventFilter;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventFilter.get(eventFilter);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventFilter.put(eventFilter, subscriptions);
        } else {
            if (subscriptions.size() > 0) {
                Subscription subscription = subscriptions.get(0);
                // 已经存在一个订阅者了，而且这个订阅者比较大牌，是排他的，所以其他的订阅者就不能再加进来了。
                if (subscription.subscriberMethod.exclusive)
                    return;
            }
            // harryguo: 这是多余代码所以我注释了，理由：newSubscription是新new出来的，subscriptions当然不可能会contains它啊
//            if (subscriptions.contains(newSubscription)) {
//                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventFilter);
//            }
        }

        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        List<String> subscribedEvents = filtersBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            filtersBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventFilter);

        if (subscriberMethod.sticky) {
            Object stickyEvent = stickyEventsByFilter.get(eventFilter);
            // 要检查一下参数是否合法。因为有些用户可能抛一个非法参数
            if (subscriberMethod.eventType.isInstance(stickyEvent))
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }

    private void unsubscribeByEventFilter(Object subscriber, String eventFilter) {
        List<Subscription> subscriptions = subscriptionsByEventFilter.get(eventFilter);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscriber == null || subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                    // harryguo：idsBySubscriber里的数据也要清一下
                    List<String> subscribedIds = filtersBySubscriber.get(subscription.subscriber);
                    if (subscribedIds != null) {
                        subscribedIds.remove(eventFilter);
                        if (subscribedIds.isEmpty())
                            filtersBySubscriber.remove(subscription.subscriber);
                    }
                }
            }
            // harryguo: 如果订阅者都已经被删光了，那这个eventFilter的记录就可以整体被删掉了
            if (subscriptions.isEmpty())
                subscriptionsByEventFilter.remove(eventFilter);
        }
    }

    public boolean hasSubscriberForEvent(String eventFilter) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventFilter.get(eventFilter);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            return true;
        }
        return false;
    }

    public Object process(Object eventContent) {
        return process(eventContent, null);
    }

    public Object process(Object eventContent, String eventFilter) {
        Object retValue = null;
        boolean subscriptionFound = false;
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            if (TextUtils.isEmpty(eventFilter)) {
                // 支持EventBus的原始调用方式（无eventFilter，只有eventContent的方式）
                subscriptions = subscriptionsByEventType.get(eventContent.getClass());
            }
            else {
                subscriptions = subscriptionsByEventFilter.get(eventFilter);
            }
        }
        // 只调用一个处理者
        if (subscriptions != null && !subscriptions.isEmpty()) {
            Subscription subscription = subscriptions.get(0);
            /**
             * 检查订阅者的threadMode，如果订阅者不希望直接调用的话，就只能post了。此时返回值是null
             * 在这种情况下，订阅者是不能调用 {@link #cancelEventDelivery(Object)}的。因为本就只调用你一个人呀。如果调用，就会抛出exception
             * */
            if (subscription.subscriberMethod.threadMode != ThreadMode.POSTING) {
                postToSubscription(subscription, eventContent, isMainThread());
                subscriptionFound = true;
            }
            else {
                Class<?> eventType = subscription.subscriberMethod.eventType;
                if (eventContent == null || (eventType != null && eventType.isInstance(eventContent))) {
                    try {
                        retValue = subscription.subscriberMethod.method.invoke(subscription.subscriber, eventContent);
                    } catch (InvocationTargetException e) {
                        handleSubscriberException(subscription, eventContent, e.getCause());
                    } catch (IllegalAccessException e) {
                        throw new IllegalStateException("Unexpected exception", e);
                    }
                    subscriptionFound = true;
                }
            }
        }
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                logger.log(Level.FINE, "No subscribers registered for event " + (eventContent == null ? null : eventContent.getClass()) + " filter:" + eventFilter);
            }
            if (sendNoSubscriberEvent) {
                post(new NoSubscriberEvent(this, eventContent));
            }
        }
        return retValue;
    }

    /**
     * Posts the given event to the event bus and holds on to the event (because it is sticky). The most recent sticky
     * event of an event's type is kept in memory for future access by subscribers using {@link Subscribe#sticky()}.
     */
    public void postSticky(Object event, String filter) {
        synchronized (stickyEventsByFilter) {
            stickyEventsByFilter.put(filter, event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event, filter);
    }

    /**
     * Removes the sticky event by filter.
     * @return true if the events matched and the sticky event was removed.
     */
    public boolean removeStickyEventByFilter(String filter) {
        synchronized (filtersBySubscriber) {
            return filtersBySubscriber.remove(filter) != null;
        }
    }

    /** Posts the given event to the event bus. */
    public void post(Object event) {
        post(event, null);
    }

    /** Posts the given event to the event bus, with event id. */
    public void post(Object event, String eventFilter) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<PostingThreadState.EventMessage> eventQueue = postingState.eventQueue;
        eventQueue.add(new PostingThreadState.EventMessage(event, eventFilter));

        if (!postingState.isPosting) {
            postingState.isMainThread = isMainThread();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

    private boolean postSingleEventForEventFilter(PostingThreadState.EventMessage eventMsg, PostingThreadState postingState) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventFilter.get(eventMsg.eventFilter);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                // 这里需要检验一下用户抛来的参数event的类型对不对。如果不对就不要去调用了，避免在调用时抛出异常了
                if (subscription.subscriberMethod.eventType.isInstance(eventMsg.event)) {
                    postingState.event = eventMsg.event;
                    postingState.subscription = subscription;
                    boolean aborted = false;
                    try {
                        postToSubscription(subscription, eventMsg.event, postingState.isMainThread);
                        aborted = postingState.canceled;
                    } finally {
                        postingState.event = null;
                        postingState.subscription = null;
                        postingState.canceled = false;
                    }
                    if (aborted) {
                        break;
                    }
                }
            }
            return true;
        }
        return false;
    }
    // harryguo end。以上全是harryguo的代码，有harryguo start做开始。
}
